import { useState, useEffect } from 'react';
import { Space, Table, Tag, Button, Modal } from 'antd';
import instance from '../../axios/index';
import { Pagination as PaginationComp } from 'antd';
import { showSuccessToast, showFailToast } from 'vant';

export default function Doctor() {
    // 定义一个状态变量list，用于存储医生数据
    const [list, setList] = useState([]);
     //当前页码状态
  const [currentPage, setCurrentPage] = useState(1);
  // 每页显示数据条数
  const [pageSize, setPageSize] = useState(5);
   const render=()=>{
          instance.post('/api/doctorauditfind').then(res => {
            let data = res.data.data.map(item => {
                const storedDisabledState = localStorage.getItem(`buttonDisabled_${item.id}`);
                return {
                  ...item,
                    buttonDisabled: storedDisabledState === 'true'
                };
            });
            setList(data);
        });
    }
  useEffect(()=>{
    render()
  },[])
    // 定义表格的列
    const columns = [
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '地址',
            dataIndex: 'city',
            key: 'city',
        },
        {
            title: '科室',
            dataIndex: 'administrativeOffice',
            key: 'administrativeOffice',
        },
        {
            title: '状态',
            key: 'flag',
            dataIndex: 'flag',
            render: (_, { flag }) => {
                let color;
                if (flag === '待审核') {
                    color = 'blue';
                } else if (flag === '审核成功') {
                    color = 'green';
                } else {
                    color = 'red'; // 其他情况使用蓝色
                }
                return (
                    <Tag color={color} key={flag}>
                        {flag.toUpperCase()}
                    </Tag>
                );
            }
        },
        {
            title: '营业执照编号',
            key: 'identitycard',
            dataIndex: 'identitycard',
        },
        {
            title: '照片',
            key: 'img',
            dataIndex: 'img',
            render: (img: any) => (
                <img src={img} alt="医生照片" style={{ width: '50px', height: '50px' }} />
            )
        },
        {
            title: '毕业学校',
            key: 'nosocomium',
            dataIndex: 'nosocomium',
        },
        {
            title: '身份',
            key: 'state',
            dataIndex: 'state',
        },
        {
            title: '操作',
            key: 'operation',
            render: (_: any, record: { id: any; }) => (
                <Space size="middle">
                    <Button type='link' danger onClick={() => delList(record.id)}>删除</Button>
                </Space>
            )
        },
        {
            title: '审核',
            key: 'operation',
            render: (_: any, record: { id: any; }) => (
                <Space size="middle">
                    <a onClick={() => querenshanchu(record.id, record.name, record)} disabled={record.buttonDisabled}>确认</a>
                    <Button type='link' danger onClick={() => loss(record.id, record.name, record)} disabled={record.buttonDisabled}>取消</Button>
                </Space>
            )
        },
    ];

    // 删除
    const delList = (id: any) => {
        Modal.confirm({
            title: '删除',
            content: '确认删除吗?',
            onOk: () => {
                instance.post('/api/doctorauditdel', { id }).then(res => {
                    if (res.data.code === 200) {
                        showSuccessToast('删除成功');
                         render()
                        // 成功删除后，清除本地存储中对应这条数据的按钮禁用状态记录
                        localStorage.removeItem(`buttonDisabled_${id}`);
                    }
                })
            }
        })
    }

    // 审核成功
    const querenshanchu = (id: any, name: any, record: any) => {
        // 设置当前行按钮为禁用状态
        const updatedList = list.map(item => {
            if (item.id === record.id) {
                return {
                  ...item,
                    buttonDisabled: true
                };
            }
            return item;
        });
        setList(updatedList);

            instance.post('/api/doctorauditpass', { id, name }).then(res => {
            if (res.data.code === 200) {
                localStorage.setItem('doctor', name);
                showSuccessToast('审核成功');

                 render()
            }
            // 无论请求成功与否，操作完成后更新本地存储中对应行的按钮禁用状态
            updateDisabledForRow(record.id, true);
        })
   
        
    }

    // 审核不通过拒绝
    const loss = (id: any, name: any, record: any) => {
        // 设置当前行按钮为禁用状态
        const updatedList = list.map(item => {
            if (item.id === record.id) {
                return {
                  ...item,
                    buttonDisabled: true
                };
            }
            return item;
        });
        setList(updatedList);

        instance.post('/api/doctorauditupdate', { id, name }).then(res => {
            if (res.data.code === 200) {
                showFailToast('已拒绝');
                
                 render()
            }
            // 无论请求成功与否，操作完成后更新本地存储中对应行的按钮禁用状态
            updateDisabledForRow(record.id, true);
        })
    }
  useEffect(()=>{
instance.post('/api/doctorauditfind').then(res => {
            let data = res.data.data.map(item => {
                const storedDisabledState = localStorage.getItem(`buttonDisabled_${item.id}`);
                return {
                  ...item,
                    buttonDisabled: storedDisabledState === 'true'
                };
            });
            setList(data);
        });

  },[])
    
    // 用于更新本地存储中指定行按钮禁用状态的函数，同时更新list状态中的对应行状态
    const updateDisabledForRow = (rowId: any, newState: any) => {
        const updatedList = list.map(item => {
            if (item.id === rowId) {
                return {
                  ...item,
                    buttonDisabled: newState
                };
            }
            return item;
        });
        setList(updatedList);
        localStorage.setItem(`buttonDisabled_${rowId}`, newState.toString());
    };

    return (
        <div>
            <Table
        rowKey="id"
        columns={columns}
        dataSource={list.slice((currentPage - 1) * pageSize, currentPage * pageSize)}
      />
       <PaginationComp
        current={currentPage}
        pageSize={pageSize}
        total={list.length}
        onChange={(page, pageSize) => {
          setCurrentPage(page);
          setPageSize(pageSize);
        }}
      />
        </div>
    );
}